import sys
import toml

from PySide6.QtCore import Qt, Slot
from PySide6.QtGui import QCloseEvent, QGuiApplication, QAction, QIcon
from PySide6.QtWidgets import (
    QMainWindow,
    QApplication,
    QMessageBox,
    QWidget,
)
from PySide6.QtPdfWidgets import QPdfView

from .Core.Widgets import PdfWidget
from os.path import dirname, abspath, join

CurrDir = dirname(abspath(__file__))
ConfigPath = join(CurrDir, "Config.toml")
IconPath = join(CurrDir,'Core/images/x01.jpg')
AppName = "x01.PdfEditor"


class MainWindow(QMainWindow):
    def __init__(
        self, parent: QWidget | None = None, flags: Qt.WindowType = Qt.Window
    ) -> None:
        super().__init__(parent, flags)
        self.setWindowTitle(AppName)
        self.setWindowIcon(QIcon(IconPath))

        self.pdfWidget = PdfWidget(self)
        self.setCentralWidget(self.pdfWidget)

        self.recentFiles = {}

        self.InitConfig()
        self.InitMenu()

    def closeEvent(self, event: QCloseEvent) -> None:
        filename = self.pdfWidget.filename
        if not filename:
            return
        if len(self.recentFiles) > 12:
            key = list(self.recentFiles.keys())[-1]
            del self.recentFiles[key]
        zoomfactor = self.pdfWidget.pdfView.zoomFactor()
        page = self.pdfWidget.pdfView.pageNavigator().currentPage()
        self.recentFiles[filename] = [float(page), zoomfactor]
        data = {
            "filename": filename,
            "lastpage": page,
            "zoomfactor": zoomfactor,
            "recentFiles": self.recentFiles,
        }
        with open(ConfigPath, "w") as f:
            toml.dump(data, f)

    def InitConfig(self):
        with open(ConfigPath, "r") as f:
            data = toml.load(f)
            if data.get("filename"):
                self.pdfWidget.filename = data["filename"]
            if data.get("lastpage"):
                self.pdfWidget.lastPage = data["lastpage"]
            if data.get("zoomfactor"):
                factor = data.get("zoomfactor")
                self.pdfWidget.pdfView.setZoomFactor(factor)
            if data.get("recentFiles"):
                self.recentFiles = data.get("recentFiles")

        if self.pdfWidget.filename:
            self.pdfWidget.OpenLast()

    def InitMenu(self):
        menubar = self.menuBar()

        self.menuFile = menubar.addMenu("&File")
        self.menuFile.addAction(self.pdfWidget.actionOpen)
        self.menuFile.addSeparator()
        self.menuRecentFiles = self.menuFile.addMenu("&Recent Files")
        for filename in self.recentFiles.keys():
            a = QAction(filename, self, triggered=self.OpenFile)
            a.setData(filename)
            self.menuRecentFiles.addAction(a)
        action = QAction("&Quit", self, shortcut="Ctrl+Q", triggered=self.Quit)
        self.menuFile.addAction(action)

        self.menuHelp = menubar.addMenu("&Help")
        self.menuHelp.addAction(QAction("&About", self, triggered=self.About))

    @Slot()
    def OpenFile(self):
        a = self.sender()
        if isinstance(a, QAction):
            filename = a.data()
            currfile = self.pdfWidget.filename
            if currfile == filename:
                return
            page = self.pdfWidget.pdfView.pageNavigator().currentPage()
            factor = self.pdfWidget.pdfView.zoomFactor()
            self.recentFiles[currfile] = [float(page), factor]
            page, factor = tuple(self.recentFiles[filename])
            self.pdfWidget.pdfView.setZoomFactor(factor)
            self.pdfWidget.OpenFile(filename, page)

    @Slot()
    def Quit(self):
        self.close()

    @Slot()
    def About(self):
        QMessageBox.about(self, "About", f"{AppName} (c) 2023 by x01(黄雄)")


def Run():
    app = QApplication(sys.argv)
    w = MainWindow()
    w.showMaximized()
    sys.exit(app.exec())


if __name__ == "__main__":
    Run()
